<?php
include_once("_common.php");
include_once("$mw_cash[path]/cybercash.lib.php");
include_once("$g4[path]/lib/etc.lib.php");
include_once("$g4[path]/head.sub.php");

if (!$is_member)
    alert("로그인 후 이용해주세요.");

sql_query("alter table $mw_cash[membership_log_table] add ml_direct char(1) not null ", false); // 바로결제여부

$msg = '';

$ml_direct = ''; // 바로결제
$msg_direct = '';
$cash_membership = get_session("cash_membership");
if ($cash_membership && !is_array($cash_membership)) {
    $tmp = explode("@", $cash_membership);
    $ms_id = $tmp[0];
    $mi_day = $tmp[1];
    $ml_direct = '1';
    $msg_direct = "바로결제";
}

if (!$cash_membership && is_array($mi_id)) {
    $cash_membership = $mi_id;
}

$cash_membership_count = 1;
if (is_array($cash_membership))
    $cash_membership_count = count($cash_membership);

for ($i=0; $i<$cash_membership_count; $i++)
{
    if (is_array($cash_membership)) {
        $row = sql_fetch(" select * from $mw_cash[membership_item_table] where mi_id = '{$cash_membership[$i]}' ");
        $ms_id = $row[ms_id];
        $mi_day = $row[mi_day];
        $ml_direct = '1';
        $msg_direct = "바로결제";
    }
    $msg_etc = '';
        
    $sql = "select * from $mw_cash[membership_table] where ms_id = '$ms_id' ";
    $row = sql_fetch($sql);

    if (!$row) {
        $msg .= "멤버쉽[$ms_id] 이 존재하지 않습니다.\\n";
        continue;
    }

    $ms_limit_day = $row[ms_limit_day]; // 최장연장일

    $ms_name = $row[ms_name];

    $sql = "select * from $mw_cash[membership_item_table] where mi_day = '$mi_day' and ms_id = '$ms_id'";
    $list = sql_fetch($sql);

    if (!$list) {
        $msg .= "멤버쉽 [{$ms_name} {$mi_day}일] 상품이 존재하지 않습니다.\\n";
        continue;
    }

    if ($list[mi_renew]) {
        $tmp = sql_fetch(" select * from $mw_cash[membership_log_table] where mb_id = '$member[mb_id]' and ms_id = '$ms_id' and ml_day = '$mi_day' and ml_edate > '$g4[time_ymdhis]' ");
        if (!$tmp) {
            $msg .= "멤버쉽 [{$ms_name} {$mi_day}일] 상품은 연장만 가능합니다.\\n";
            continue;
        }
    }

    // 아직 유효한 멤버쉽이 있다면 종료날짜 + 추가기간
    $sql = "select * from $mw_cash[membership_log_table] where mb_id = '$member[mb_id]' and ml_edate >= '$g4[time_ymdhis]' and ms_id = '$ms_id' order by ml_edate desc limit 1";
    $row = sql_fetch($sql);

    if ($row)
        $ml_sdate = date("Y-m-d H:i:s", strtotime($row[ml_edate]) + 1);
    else
        $ml_sdate = $g4[time_ymdhis];

    $ml_edate = date("Y-m-d H:i:s", strtotime($ml_sdate) + ($list[mi_day] * 60*60*24)) ;

    if ($ms_limit_day) {
        $limit_day = date("Y-m-d H:i:s", $g4[server_time] + ($ms_limit_day * 60*60*24));
        if ($ml_edate > $limit_day) {
            $msg .= "죄송합니다. 멤버쉽 [{$ms_name}]은 {$ms_limit_day}일 이상 연장하실 수 없습니다.\\n";
            continue;
        }
    }

    $discount = 0;
    if ($list[mi_discount])
        $discount = mw_cash_membership_discount($list[mi_id]);

    $cash = $list[mi_cash];
    $is_extend = false;

    if ($row[ml_edate]) { // 연장할인
        if ($list[mi_cash_extend] > $discount) {
            $discount = $list[mi_cash_extend];
            $cash = round($list[mi_cash] * ((100-$discount)/100));
            $is_extend = true;
            $msg_etc = "연장";
        }
    }

    // 장기회원 할인
    if ($list[mi_cash_join_day] && $list[mi_cash_join_sale] > $discount && $list[mi_cash_join_day] < ($g4[server_time]-strtotime($member[mb_datetime]))/(60*60*24)) {
        $discount = $list[mi_cash_join_sale];
        $cash = round($list[mi_cash]*(100-$list[mi_cash_join_sale])/100);
        $msg_etc = "장기회원";
    }

    // 컨텐츠샵 결제
    //$cl_id = mw_buy_contents2($member[mb_id], $list[mi_cash], "$ms_name 멤버쉽 ($ml_edate 종료)", $bo_table);
    $cl_id = mw_buy_contents2($member[mb_id], $cash, "$ms_name 멤버쉽 $msg_etc $msg_direct ($ml_edate 종료)", "membership", $ms_id);

    $sql = "insert into $mw_cash[membership_log_table] set cl_id = '$cl_id'
                , ms_id = '$ms_id'
                , mb_id = '$member[mb_id]'
                , ml_cash = '$cash'
                , ml_day = '$list[mi_day]'
                , ml_sdate = '$ml_sdate'
                , ml_edate = '$ml_edate'
                , ml_direct = '$ml_direct'
                , ml_datetime = '$g4[time_ymdhis]'";
    sql_query($sql);

    $msg .= "멤버쉽 [{$ms_name} {$mi_day}일] 가입처리 되었습니다.\\n";
}

$tmp = explode("@", get_session("download_membership"));
set_session("cash_contents", '');
set_session("cash_membership", '');
set_session("download_membership", '');

if ($cash_membership && get_session("download_membership_popup"))
{
    set_session("download_membership_popup", '');
    $board = sql_fetch("select bo_skin from $g4[board_table] where bo_table = '$tmp[0]'");
    $url = "$g4[path]/skin/board/$board[bo_skin]/mw.proc/download.popup.skin.php?bo_table=$tmp[0]&wr_id=$tmp[1]&no=$tmp[2]";
    if ($msg) {
        ?>
        <script type="text/javascript">
        window.onload = function () {
            alert("<?=$msg?>");
            location.href = "<?=$url?>";
        }
        </script>
        <?
    }
}
else
{
    ?>
    <script type="text/javascript">
    window.onload = function () {
        alert("<?=$msg?>");
        opener.location.reload();
        self.close();
    }
    </script>
    <?
}
include_once("$g4[path]/tail.sub.php");
